<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document Encryption Setup</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      background-color: #f4f4f4;
    }

    form {
      width: 80%;
      max-width: 800px;
      background: white;
      padding: 2em;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    h2 {
      text-align: center;
      margin-bottom: 1em;
    }

    label {
      display: block;
      margin-top: 1em;
    }

    textarea,
    input[type="text"],
    input[type="password"] {
      width: 100%;
      padding: .5em;
      margin-top: .5em;
      border: 1px solid #ddd;
      border-radius: 5px;
    }

    button {
      display: block;
      width: 100%;
      padding: 1em;
      margin-top: 1em;
      background: #007BFF;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    button:hover {
      background: #0056b3;
    }

    .fileList {
      margin-top: 1em;
    }

    .fileList table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 1em;
    }

    .fileList th, .fileList td {
      padding: 8px;
      text-align: left;
      border: none;
    }

    .fileList th {
      background-color: #f2f2f2;
      border-bottom: none;
    }

    .fileList tr:last-child td {
      border-bottom: none;
    }

    .fileList td:first-child {
      border-left: none;
    }

    .fileList td:last-child {
      border-right: none;
    }

    .fileList button {
      padding: .5em;
      margin-top: 0;
      border-radius: 5px;
      background: #ff5c5c;
      color: white;
      border: none;
      cursor: pointer;
    }

    .fileList button:hover {
      background: #e64a4a;
    }

    .fileList .fileEntry:last-child {
      margin-bottom: 0;
    }
    /* 可选：为按钮添加样式 */
    #uploadButton {
      padding: 10px 20px;
      background-color: #007bff;
      color: white;
      border: none;
      cursor: pointer;
      font-size: 16px;
    }

    #uploadButton:hover {
      background-color: #0056b3;
    }

  </style>
  <script src="https://anquan.baidu.com/webstatic/lib/jquery.min.js"></script>
</head>
<body>
<form id="encryptionForm">
  <h2>加密工具设置</h2>

  <div class="fileList">
    <table>
      <thead>
      <tr>
        <th>文件地址</th>
        <th>文件名称</th>
        <th>文件类型</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr class="fileEntry">
        <td><input type="text" name="filePath1" placeholder="File Path" value="c:/test.pdf"></td>
        <td><input type="text" name="fileName1" placeholder="File Name" value="test.pdf"></td>
        <td><input type="text" name="fileType1" placeholder="File Type" value="pdf"></td>
        <td>
          <button type="button" onclick="removeFileEntry(this)">Remove</button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>

  <button type="button" onclick="addFileEntry()">添加文件</button>

  <label for="zipName">加密文件压缩包名称:</label>
  <input type="text" id="zipName" name="zipName" value="test.zip">

  <label for="zipName"> 加密文件输出地址:</label>
  <input type="text" id="encryptedFileExportPath" name="encryptedFileExportPath" value="C:/demo/">

  <h3>CA互认共享组件配置</h3>
  <label for="tradingSystemCode">交易系统编码:</label>
  <input type="text" id="tradingSystemCode" name="tradingSystemCode" value="">

  <label for="caServiceUrl">CA Service Url (CA互认共享组件服务地址):</label>
  <input type="text" id="caServiceUrl" name="caServiceUrl" value="">

  <label for="clientId">Client ID (客户端ID):</label>
  <input type="text" id="clientId" name="clientId" value="">

  <label for="clientSecret">Client Secret (客户端密钥):</label>
  <input type="text" id="clientSecret" name="clientSecret" value="">

  <label for="signatureSecret">Signature Secret(签名密钥):</label>
  <input type="text" id="signatureSecret" name="signatureSecret" value="">

  <button type="button" onclick="onStart()">启动工具</button>

  <input type="file" name="upload" id="upload" style="display: none;" />
  <button type="button" id="uploadFileButton">加密文件上传</button>
  <input type="hidden" id="fileName">
  <button type="button" id="decryptFileButton" onclick="decryptFile()">解密文件</button>
  <img id="deQrCode" src="" alt="解密二维码" style="display: none;">
  <a href="https://d45a52.link.yunpan.com/lk/surl_y9ktHkJQ6Kr#/">ca互认工具下载</a>
</form>

<script>
  $('#uploadFileButton').click(function () {
    $('#upload').click();
  });
  $('#upload').click(function () {
    $('#upload').val('');
  });
  //第一步 上传加密文件
  $('#upload').on('change', function(){
    const file = this.files[0];
    const formData = new FormData();
    formData.append('file', file);
    // 发送 AJAX 请求
    $.ajax({
      url: '/nation/upload', // 替换为你的服务器端点
      type: 'POST',
      data: formData,
      contentType: false, // 不设置内容类型
      processData: false, // 不处理数据
      success: function(response) {
        console.log('File uploaded successfully:', response);
        if(response.code===200){
          $('#fileName').val(response.fileName)
          alert('文件上传成功！');

        }
      },
      error: function(error) {
        console.error('File upload failed:', error);
        alert('文件上传失败！');
      }
    });
  });

  //第二步:解压文件
  function unzipFile(fileKey){
    return  $.ajax({
      url: '/nation/unzipFile',
      type: 'POST',
      data: {
        fileKey: fileKey
      },
      dataType: 'json'
    })
  }
  //第三步:生成解密二维码
  function generateDeQRCode(decyptUserType,threeInOneCode,idCardHash) {
    return    $.ajax({
      url: '/nation/getDeQrCode?decyptUserType='+decyptUserType+'&threeInOneCode='+threeInOneCode+'&idCardHash='+idCardHash,
      dataType: 'json',
      type: 'get',
      // success: function(data) {
      //   console.log(data);
      //   if(data.code==0){
      //     $('#decryptTid').val(data.data.tid);
      //     $('#deQrCode').attr('src', 'data:image/png;base64,'+data.data.qrCodeImageBase64);
      //     $('#deQrCode').show();
      //
      //     intervalId = setInterval(function(){
      //       queryDeScannedStatus(data.data.tid,intervalId)
      //     }, 1000)
      //   }
      // },
      // error: function(xhr, status, error) {
      //   console.log(error);
      // }
    }
    );
  }

  //获取解密用户信息
  function getDecryptToken(tid){
    return  $.ajax({
      url: '/nation/getDecryptUserInfo?tid='+tid,
      dataType: 'json',
      type: 'get',
    });
  }
  //上传信封信息
  function uploadEnvelope(envelope){
    $.ajax({
      url: '/nation/uploadEncryptEnvelope',
      dataType: 'json',
      data:JSON.stringify(envelope),
      type: 'post',
      contentType: 'application/json;charset=UTF-8',
      success: function(data) {
        console.log('上传信封信息:')
        console.log(data);
        if(data.code===0){
          alert('信封信息上传成功！,请在app输入pin码')
          intervalId=setInterval(function (){
            getDecryptMsg(envelope.tid,intervalId)
          },1000)
        }

      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }
  function decryptUnzipFile(fileKey,decryptPassword){
    $.ajax({
      url: '/nation/decyptFile?fileKey='+fileKey+'&decryptPassword='+decryptPassword,
      dataType: 'json',
      type: 'get',
      success: function(data) {
        console.log('解密文件:')
        console.log(data);
        if(data.code===200){
          alert('文件解密成功:');
          window.open('/nation/download?fileName='+fileKey.substring(0,fileKey.lastIndexOf('.')))

        }else{
          alert('文件解密失败:');
        }
      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }
  //获取解密信息
  function getDecryptMsg(tid,intervalId) {
    $.ajax({
      url: '/nation/getDecryptMsg?tid='+tid,
      dataType: 'json',
      type: 'get',
      success: function(data) {
        console.log('解密结果:')
        console.log(data);
        if(data.code==0&&data.data instanceof Array&&data.data.length>0&&data.data[0].decryptStatus=='0'){
          clearInterval(intervalId);
          //获取解密密钥成功
          var key=data.data[0].decryptedKey
          console.log('解密密钥成功:'+key)
          //调用解密文件接口进行解密
          decryptUnzipFile($('#fileName').val(),key)
          //$('#deMsg').val(JSON.stringify(data.data))
        }
      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }
  //获取解密二维码扫描状态
  function queryDeScannedStatus(tid,intervalId,envelope) {
    $.ajax({
      url: '/nation/queryDeScannedStatus?tid='+tid,
      dataType: 'json',
      type: 'get',
      success: function(data) {
        console.log(data);
        if(data.code==0){
          if(data.data.scannedStatus=='00'){
            $('#loginStatus').text('未扫描');
          }else if(data.data.scannedStatus=='03'){
            //扫码之后状态就直接03了,获取用户token，上传信封信息
            clearInterval(intervalId);
            //获取用户token
            getDecryptToken(tid).then(function (res){
              console.log('获取解密用户信息成功:')
              console.log(res)
              if(res.code===0){
                var token=res.data.accessToken
                envelope.accessToken=token
                //上传信封信息
                uploadEnvelope(envelope)
              }
            })
          }else if(data.data.scannedStatus=='01'){
            console.log('已扫码未授权 ')
          }else if(data.data.scannedStatus=='02'){
            clearInterval(intervalId);
            console.log('已失效')
          }
          else{
            clearInterval(intervalId);
            $('#loginStatus').text('未知状态');
          }
        }

      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }
  function decryptFile() {
    const fileName = $('#fileName').val()
    if(!fileName){
      alert('请先上传文件！')
      return
    }
    unzipFile(fileName).then(function (res) {
      if(res.code === 200){
        //生成解密二维码
        var unData=res.data
        console.log('解压缩文件成功:')
        console.log(unData)
        //生成解密二维码
        generateDeQRCode(unData.decyptUserType,unData.orgCode,unData.idCardHash).then(function (gres){
          if(gres.code===0){
            console.log('生成解密二维码成功')
            var tid=gres.data.tid
            $('#deQrCode').attr('src', 'data:image/png;base64,'+gres.data.qrCodeImageBase64);
            $('#deQrCode').show();

            //封装信封信息
            encryptedKeyDataEnvelopeList=unData.encryptedKeyDataEnvelopeList
            var envelope={
              'tid':tid,
              'accessToken':'',
              'encryptedKeyDataEnvelopeList':encryptedKeyDataEnvelopeList
            }
            //轮询扫码状态
            intervalId = setInterval(function(){
              queryDeScannedStatus(gres.data.tid,intervalId,envelope)
            }, 1000)

          }
        })
      }else{
        alert('文件解压失败！')
      }
    })
  }
</script>
<script>
  let socket
  let isConnect = false
  let isConnecting = false
  let socketData

  //获取配置信息
  function getConfig(){
    return  $.ajax({
      url: '/nation/getconfig',
      type: 'GET',
      dataType: 'json'
    })
  }

  $(function (){
    getConfig().then(function (res){
      if(res.code === 0){
        $('#tradingSystemCode').val(res.data.platformCode)
        $('#caServiceUrl').val(res.data.apiUrl)
        $('#clientId').val(res.data.clientId)
        $('#clientSecret').val(res.data.clientSecret)
        $('#signatureSecret').val(res.data.signatureSecret)
      }
    })
  })

  function connectWebSocket() {
    isConnecting = true
    socket = new WebSocket('ws://localhost:12345')
    socket.binaryType = 'JSON'
    socket.onopen = (event) => {
      isConnect = true
      console.log('WebSocket is open now.')
    }

    socket.onmessage = (event) => {
      if (socketData) {
        socket.send(socketData)
        socketData = undefined
      }
      console.log('Received data from server: ', event.data)
    }

    socket.onclose = (event) => {
      isConnect = false
      isConnecting = false
      console.log('WebSocket is onclose now.')
    }

    socket.onerror = (error) => {
      isConnect = false
      connectWebSocket()
      console.error('WebSocket Error: ', error)
    }
  }




  function addFileEntry() {
    const fileList = document.querySelector('.fileList tbody')
    const nextIndex = fileList.childElementCount + 1;
    const entryTemplate = `
        <tr class="fileEntry">
            <td><input type="text" name="filePath${nextIndex}" placeholder="File Path"></td>
            <td><input type="text" name="fileName${nextIndex}" placeholder="File Name"></td>
            <td><input type="text" name="fileType${nextIndex}" placeholder="File Type"></td>
            <td><button type="button" onclick="removeFileEntry(this)">Remove</button></td>
        </tr>
    `
    fileList.insertAdjacentHTML('beforeend', entryTemplate);
  }

  function removeFileEntry(button) {
    const entry = button.closest('tr')
    entry.parentNode.removeChild(entry)
  }

  function onStart() {
    const formData = new FormData(document.getElementById('encryptionForm'))
    const data = {
      CAShareUseScene: '01',
      keyParameter: {
        awaitingEncryptionFileList: [],
        encryptedFileZipName: formData.get('zipName'),
        encryptedFileExportPath: formData.get('encryptedFileExportPath'),
        caShareComponentConfig: {
          tradingSystemCode: formData.get('tradingSystemCode'),
          caShareComponentServiceUrl: formData.get('caServiceUrl'),
          clientId: formData.get('clientId'),
          clientSecret: formData.get('clientSecret'),
          signatureSecret: formData.get('signatureSecret')
        }
      }
    }

    for (const [key, value] of formData.entries()) {
      if (key.startsWith('filePath')) {
        const entryKey = key.replace('filePath', '')
        data.keyParameter.awaitingEncryptionFileList.push({
          awaitingEncryptionFilePath: value,
          awaitingEncryptionFileName: formData.get(`fileName${entryKey}`),
          fileType: formData.get(`fileType${entryKey}`)
        })
      }
    }
    socketData = JSON.stringify(data)
    console.log(socketData)
    window.location.href = 'CAShareDetectInstallTool://websocket?flag=1'
    if (!isConnect) {
      if (!isConnecting) {
        connectWebSocket()
      }
    } else {
      socket.send(socketData)
      socketData = undefined
    }
  }
</script>
</body>
</html>
